using Microsoft.AspNetCore.Mvc.ViewFeatures;
using Microsoft.AspNetCore.Razor.TagHelpers;
using System.Buffers.Text;
using System.Collections.Generic;
using System.Text;
using System.Text.Json;
using WalkingTec.Mvvm.Core;

namespace ReaWTM.LayuiHelper
{
	[HtmlTargetElement("wt:form", Attributes = REQUIRED_ATTR_NAME, TagStructure = TagStructure.NormalOrSelfClosing)]
	public class FormTagHelper : BaseElementTag
	{

		protected const string REQUIRED_ATTR_NAME = "vm";
		public const string FORM_ID_PREFIX = "wtForm_";

		private string _id = null;
		public new string Id
		{
			get
			{
				if (string.IsNullOrEmpty(_id))
				{
					if (Vm?.Model is IBaseVM)
					{
						var vm = Vm.Model as IBaseVM;
						_id = $"{FORM_ID_PREFIX}{vm.UniqueId}";
					}
					else if (Vm?.Model is BaseSearcher)
					{
						var vm = Vm.Model as BaseSearcher;
						_id = $"{FORM_ID_PREFIX}{vm.UniqueId}";
					}
				}
				return _id;
			}
			set
			{
				_id = value;
			}
		}


		/// <summary>
		/// 提交表单的Url
		/// </summary>
		public string Url { get; set; }

		/// <summary>
		/// 表单绑定的Vm
		/// </summary>
		public ModelExpression Vm { get; set; }

		/// <summary>
		/// 提交前调用的js
		/// </summary>
		public string BeforeSubmit { get; set; }

		/// <summary>
		/// 使用传统表单提交方式提交，而不使用 AJAX 提交
		/// 比如登陆页面，提交后校验成功会跳转其他页面，而不是返会 PartialView
		/// </summary>
		public bool OldPost { get; set; }
		/// <summary>
		/// 设置表单内控件前面label的长度，默认为80
		/// </summary>
		public int? LabelWidth { get; set; }
		BaseVM vm;
		void SetUrl()
		{
			if (!string.IsNullOrEmpty(Url)) return;

			//设置提交地址，如果不指定Url，默认为当前页面。如果绑定Vm为BatchVM，将提交地址由BatchXXX变为DoBatchXXX。
			//因为框架默认的Batch本身是一个Post方法，无法使用同名方法处理提交后的工作
			if (Vm.Model is IBaseBatchVM<BaseVM>)
			{
				Url = vm?.CurrentUrl.Replace("/Batch", "/DoBatch") ?? "#";
			}
			else
			{
				Url = vm?.CurrentUrl ?? "#";
			}
		}
		string ErrorMsg;
		string GetErrors()
		{
			var errors = new List<object>();

			//输出后台返回的错误信息
			if (vm?.MSD?.Count > 0)
			{
				foreach (var key in vm.MSD.Keys)
				{
					foreach (var item in vm.MSD[key])
					{
						errors.Add(new
						{
							key = key,
							value = item.ErrorMessage
						});
					}

				}
				ErrorMsg = vm.MSD.GetFirstError();
			}

			var rv = JsonSerializer.Serialize(errors, JsonOptions2);
			if (string.IsNullOrEmpty(rv))
			{
				return "[]";
			}
			else
			{
				return rv;
			}
		}


		public override void Process(TagHelperContext context, TagHelperOutput output)
		{
			vm = Vm.Model as BaseVM;

			SetCascadeValue(context, this);
			SetUrl();

			//将id传给dialog
			UseCascadeParameter<DialogTagHelper>(context, x =>
			{
				x.SetDictValue("formId", Id);

			});

			StringBuilder ptx = new StringBuilder();
			StringBuilder post = new StringBuilder();

			output.TagName = "form";
			output.TagMode = TagMode.StartTagAndEndTag;
			output.Attributes.SetAttribute("id", Id);
			output.Attributes.SetAttribute("class", "layui-form wtm-form");
			output.Attributes.SetAttribute("lay-filter", Id);
			output.Attributes.SetAttribute("action", Url);
			output.Attributes.SetAttribute("method", "post");

			//添加一个隐藏的提交按钮
			ptx.Append($@"<a hidden lay-submit lay-filter='submit{Id}' id='submit{Id}'/>");
			ptx.Append($@"
<script>
wtm.form_Render({{
id:'{Id}',
url:'{Url}',
isOld:{GetBooleanString(OldPost)},
divId:'{vm.ViewDivId}',
errorMsg:'{ErrorMsg}',
errors:{GetErrors()},
beforeSubmit:'{BeforeSubmit}',
beforeMount:'{BeforeMount}',
mounted:'{Mounted}',

}});
</script>
");
			output.PostContent.AppendHtml(ptx.ToString());
			output.PostElement.AppendHtml(post.ToString());



			base.Process(context, output);
		}
	}
}
